package com.hknc.btscale.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetWorkEtheret extends BroadcastReceiver {
    public int NET_ETHERNET = 1;
    public int NET_WIFI = 2;
    public int NET_NOCONNECT = 0;
    private WifiStatus mWifiStatus;

    public WifiStatus getWifiStatus() {
        return mWifiStatus;
    }

    public void setWifiStatus(WifiStatus wifiStatus) {
        mWifiStatus = wifiStatus;
    }

    public interface WifiStatus {
        void isConnect(boolean isConnect);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (action.equals(
                ConnectivityManager.CONNECTIVITY_ACTION)
                || action.equals(
                "android.net.conn.CONNECTIVITY_CHANGE")) {

            switch (isNetworkAvailable(context)) {
                case 1:
                    System.out.println("-----------networktest---------有线");
                    mWifiStatus.isConnect(true);
                    break;
                case 2:
                    System.out.println("-----------networktest---------无线");
                    mWifiStatus.isConnect(false);
                    break;
                case 0:
                    System.out.println("-----------networktest---------无网络");
                    mWifiStatus.isConnect(false);
                    break;
                default:
                    break;
            }
        }
    }

    private int isNetworkAvailable(Context context) {
        ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ethNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (ethNetInfo != null && ethNetInfo.isConnected()) {
            return NET_ETHERNET;
        } else if (wifiNetInfo != null && wifiNetInfo.isConnected()) {
            return NET_WIFI;
        } else {
            return NET_NOCONNECT;
        }
    }
}
